<template>
    <div id="student">
        <el-breadcrumb class="common-bread">
            <el-breadcrumb-item>学生管理</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="select mt10">
            <label class="label">学校：</label>
            <el-autocomplete v-model="schoolName" :fetch-suggestions="querySearch" placeholder="请输入学校名称"
                @select="handleSelect" clearable></el-autocomplete>
            <label class="label">年级：</label>
            <el-select v-model="gradeId" @change="getClasses()">
                <el-option label='全部' value='0'></el-option>
                <el-option :label='item.gradeName' :value='item.gradeId' :key='item.gradeId' v-for="item in grades">
                </el-option>
            </el-select>
            <label class="label">班级：</label>
            <el-select v-model="classId">
                <el-option label='全部' value='0'></el-option>
                <el-option :label='item.name' :value='item.classId' :key='item.classId' v-for="item in classes">
                </el-option>
            </el-select>
            <label class="label">学生状态：</label>
            <el-select v-model="status">
                <el-option label='全部' value='-1'></el-option>
                <el-option label='在校' value='0'></el-option>
                <el-option label='已毕业' value='1'></el-option>
                <el-option label='已转校' value='2'></el-option>
                <el-option label='已开除' value='3'></el-option>
            </el-select>
        </div>

        <div class="contentBox">
            <div>
                <label class="label">学生：</label>
                <el-input placeholder="请输入 姓名/学籍号" v-model="keywords" class="keyword"></el-input>
                <el-button type="primary" @click="getList(1)">搜索</el-button>
                <el-button type="primary" @click="newStu()" class="fr" icon="el-icon-circle-plus-outline">添加学生
                </el-button>
                <el-button type="primary" @click="toImportStu()" class="fr">导入学生</el-button>
            </div>
            <div class="list">
                <el-table :data="list">
                    <el-table-column type="index" label="序号">
                    </el-table-column>
                    <el-table-column prop="name" label="学生姓名">
                    </el-table-column>
                    <el-table-column prop="gender" label="性别">
                    </el-table-column>
                    <el-table-column prop="nation" label="民族">
                    </el-table-column>
                    <el-table-column prop="birthday" label="出生日期">
                    </el-table-column>
                    <el-table-column prop="studentNumber" label="学籍号">
                    </el-table-column>
                    <el-table-column prop="number" label="编号">
                    </el-table-column>
                    <el-table-column prop="className" label="班级">
                    </el-table-column>
                    <el-table-column prop="parents" label="家长">
                    </el-table-column>
                    <el-table-column prop="schoolName" label="学校">
                    </el-table-column>
                    <el-table-column prop="address" label="家庭住址">
                    </el-table-column>
                    <el-table-column prop="status" label="学生状态">
                    </el-table-column>
                    <el-table-column label="操作" width="150px">
                        <template slot-scope="scope">
                            <i class="el-icon-document blueIcon" @click="toDet(scope.row)" title="查看详情"></i>
                            <i class="el-icon-edit blueIcon" @click="newStu(scope.row)" title="编辑"></i>
                            <i class="el-icon-delete redIcon" @click="deleteStudent(scope.row)" title="删除"
                                v-if="scope.row.status!='已毕业'"></i>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination v-show="this.totalCount > 10" layout="total,prev, pager, next, jumper"
                        :page-size="10" :current-page="currentPage" :total="totalCount"
                        @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import { mapState, mapActions } from "vuex";

    export default {
        data() {
            return {
                schools: [],
                schoolName: "",
                gradeId: "0",
                classes: [],
                classId: "0",
                status: "0",
                options: new Map([["-1", "全部"], ["0", "在校"], ["1", "已毕业"], ["2", "已转校"], ["3", "已开除"]]),
                grades: this.$util.getGrades(),
                keywords: "",
                list: [],
                totalCount: 0,
                currentPage: 1
            }
        },
        computed: mapState({ user: state => state.user }),
        mounted() {
            this.getSchool().then(() => {
                let stuInfo = JSON.parse(this.$util.getStore("stuInfo"));
                let stuSelect = this.$util.getStore("stuSelect");

                if (stuInfo && stuSelect == 1) {
                    this.currentPage = stuInfo.pageNum * 1;
                    this.schoolId = stuInfo.schoolId;
                    this.schoolName = stuInfo.schoolName;
                    this.gradeId = stuInfo.grade ? stuInfo.grade : "0";
                    this.classId = stuInfo.classId ? stuInfo.classId : "0";
                    this.status = stuInfo.status ? stuInfo.status : "0";
                    this.keywords = stuInfo.searchKey;
                    this.schoolType = stuInfo.schoolType || ["小学", "初中", "高中"];
                    this.grades = this.$util.getGrades(this.schoolType);
                    this.getClasses(this.classId);

                    this.getList(this.currentPage);
                } else {
                    this.getList(this.currentPage);
                }

                this.$util.removeStore("stuInfo");
                this.$util.removeStore("stuSelect");

            });
        },
        methods: {
            getSchool() {
                return new Promise(resolve => {
                    this.$util.getSchools().then(schools => {
                        schools.forEach(item => {
                            let name = item.name;
                            this.schools.push({
                                value: name,
                                schoolId: item.schoolId,
                                haveHigh: item.haveHigh,
                                haveMiddle: item.haveMiddle,
                                havePrimary: item.havePrimary
                            })
                        });

                        resolve(schools);
                    });
                })
            },
            createFilter(queryString) {
                return (school) => {
                    return (school.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
                };
            },
            querySearch(queryString, cb) {
                let schools = this.schools;
                let results = queryString ? schools.filter(this.createFilter(queryString)) : schools;
                // 调用 callback 返回建议列表的数据
                cb(results);
                results = [];
            },
            handleSelect(item) {
                this.schoolId = item.schoolId;
                let schoolType = [];
                if (item.haveHigh) schoolType.push("高中");
                if (item.haveMiddle) schoolType.push("初中");
                if (item.havePrimary) schoolType.push("小学");
                this.schoolType = schoolType;
                this.grades = this.$util.getGrades(this.schoolType);
                this.gradeId = "0";
                this.getClasses("0");
            },
            //获取班级列表
            getClasses(id) {
                let params = {
                    grade: this.gradeId,
                    schoolId: this.schoolId,
                    pageSize: 100,
                    pageNum: 1
                }

                if (this.gradeId == 0) delete params.grade;
                this.$axios.get("/adminapi/v1/tools/classes/list", {
                    params: params
                }).then(response => {
                    if (response.data.error == 10000) {
                        this.classes = [];
                        if (!id) this.classId = "0";
                        if (!response.data.data) return;
                        let list = response.data.data.content;

                        list.forEach(item => {
                            let gradeName = this.$util.gradeFormat(item.grade * 1);
                            let className = gradeName + item.number + "班";
                            item.name = item.name ? className + `（${item.name}）` : className;

                            this.classes.push({
                                name: item.name,
                                classId: item.classId
                            })

                            if (id) this.classId = id;
                        })

                    }
                })
            },

            //获取学生列表
            getList(pageNum) {
                if (pageNum != this.currentPage) this.currentPage = pageNum;

                let params = {
                    pageSize: 10,
                    pageNum: pageNum * 1,
                    schoolType: this.schoolType,
                    schoolName: this.schoolName
                };

                if (this.keywords) params.searchKey = this.keywords.trim();
                if (this.gradeId != 0) params.grade = this.gradeId;
                if (this.classId != 0) params.classId = this.classId;
                if (this.status != -1) params.status = this.status;
                if (this.schoolId && this.schoolName) params.schoolId = this.schoolId;
                this.$util.setStore("stuInfo", params);
                delete params.schoolName;
                delete params.schoolType;

                this.$axios.get("/adminapi/v1/user/student/list", {
                    params: params
                }).then(response => {
                    if (response.data.error == 10000) {
                        this.list = [];
                        this.totalCount = 0;
                        if (!response.data.data) return;
                        let list = response.data.data.content;
                        this.totalCount = response.data.data.total * 1;

                        list.forEach(item => {
                            item.gender = item.gender ? "男" : "女";
                            item.grade = this.$util.gradeFormat(item.grade * 1);
                            let className = item.grade + item.claNumber + "班";
                            item.className = item.className ? className + `（${item.className}）` : className;
                            item.status = this.options.get(item.status + "");

                            if (item.studentParentModels && item.studentParentModels.length) {
                                item.parents = item.studentParentModels.map(parent => parent.name);
                                item.parents = this.unique(item.parents).join("、");
                            }

                            item.birthday = item.birthday ? new Date(item.birthday * 1).format("yyyy.MM.dd") : "";
                            this.list.push(item);
                        });
                    } else {
                        this.$util.errorMsg(response.data.message);
                    }
                })
            },
            //数组去重
            unique(list) {
                let map = new Map();
                list.forEach(item => {
                    map.set(item, item);
                })

                return [...map.keys()];
            },
            deleteStudent(row) {
                this.$confirm(`删除学生会将学生对应的体测成绩和手环数据都删除，确定要删除吗？`, "温馨提示", this.$util.confirmBtnText).then(() => {
                    this.$axios.post("/adminapi/v1/user/student/delete?studentId=" + row.studentId).then(response => {
                        if (response.data.error == 10000) {
                            this.$util.successMsg("删除成功");
                            this.getList(this.currentPage);
                        } else {
                            this.$util.errorMsg(response.data.message);
                        }
                    })
                }).catch(() => { })
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getList(val);
            },
            newStu(row) {
                this.saveSelectHistory();
                if (row) return this.$router.push('/newStudent?id=' + row.studentId);
                this.$router.push('/newStudent');
            },
            toDet(row) {
                this.saveSelectHistory();
                this.$router.push('/studentDet?id=' + row.studentId);
            },
            saveSelectHistory() {

                let params = {
                    pageSize: 10,
                    pageNum: this.currentPage,
                    schoolType: this.schoolType,
                    schoolName: this.schoolName,
                    status: this.status
                };

                if (this.keywords) params.keywords = this.keywords.trim();
                if (this.gradeId != 0) params.grade = this.gradeId;
                if (this.schoolId && this.schoolName) params.schoolId = this.schoolId;
                if (this.classId != 0) params.classId = this.classId;

                this.$util.setStore("stuInfo", params);
            },
            toImportStu() {
                this.saveSelectHistory();
                this.$router.push('/importStu');
            }
        }
    }
</script>
<style>
    #student .select {
        margin: 0 32px;
        padding: 24px;
        background-color: #fff;
    }

    #student .contentBox {
        height: calc(100% - 215px);
    }
</style>